import {
    createAGroupFolder,
    getPlayerData,
    isGroupExist,
    isPlayerExist,
    storagePlayerData,
    deletePlayerData,
    ensureGroupAndPlayerExist,
    getConfig
} from "../function/function.js";
import lodash from 'lodash'
import fs from 'fs';

// 读取JSON文件
const copywriting = JSON.parse(fs.readFileSync('plugins/Slave-Market/resources/data/workCopywriting.json', 'utf-8'))

export class Sm extends plugin {
    constructor() {
        super({
            name: '[Sm]雇佣仆人',
            dsc: '雇佣仆人',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]雇佣(群友|仆人)(\d+)?/, fnc: 'purchaseSlaves' }
            ]
        })
    }

    async purchaseSlaves(e) {
        if (!e.isGroup) return e.reply(['该游戏只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        if (e.atme) return e.reply(['不可以雇佣我捏~']);

        // 使用通用函数检查和初始化群组和玩家
        ensureGroupAndPlayerExist(ID[1], ID[0]);

        let slave = e.at;
        if (!slave) slave = e.msg.replace(/#|\/|雇佣|群友|仆人|\s/g, '');
        slave = parseInt(slave);
        if (slave === ID[0]) return e.reply(['不可以雇佣自己捏~']);

        try {
            const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);

            if (!memberInfoList[slave]) return e.reply([`本群不存在[${slave}]`]);

            slave = parseInt(slave);

            if (!isPlayerExist(ID[1], slave)) {
                storagePlayerData(ID[1], slave, {
                    currency: 0,
                    slave: [],
                    value: 100,
                    lastWorkingTime: 0,
                    master: ''
                });
            }

            const userData = await getPlayerData(ID[1], ID[0]);
            const slaveData = await getPlayerData(ID[1], slave);

            const { currency } = userData;
            const { currency: slavecurrency, value: slavevalue, master: slaveMaster } = slaveData;

            if (slaveMaster === ID[0]) return e.reply([
                segment.at(ID[0]),
                '你已经是他的主人了'
            ]);

            if (currency < slavevalue) return e.reply([
                segment.at(ID[0]),
                `你付不起雇佣金！需要${slavevalue}金币`
            ]);

            // 读取配置文件中的冷却时间
            const config = getConfig();
            const currentSecond = Math.floor(Date.now() / 1000);
            const purchaseCooldown = config.purchase.cooldown; // 从配置文件读取冷却时间

            // 检查冷却时间
            if (currentSecond - (userData.lastPurchaseTime || 0) < purchaseCooldown) {
                const remainingTime = purchaseCooldown - (currentSecond - (userData.lastPurchaseTime || 0));
                return e.reply([`雇佣冷却中，剩余时间：${Math.floor(remainingTime / 3600)}小时${Math.floor((remainingTime % 3600) / 60)}分钟`]);
            }

            // 检查是否试图雇佣雇主
            if (slave === userData.master) {
                return e.reply(lodash.sample(copywriting.buyMaster));
            }

            if (slaveMaster === '') {
                userData['currency'] = parseFloat((userData['currency'] - slavevalue).toFixed(1));
                userData['slave'].push(slave);
                userData['lastPurchaseTime'] = currentSecond;
                storagePlayerData(ID[1], ID[0], userData);
                slaveData['currency'] = parseFloat((slaveData['currency'] + slavevalue).toFixed(1));
                slaveData['value'] = parseFloat((slaveData['value'] + 20).toFixed(1));
                slaveData['master'] = ID[0];
                storagePlayerData(ID[1], slave, slaveData);

                return e.reply([`成功雇佣了${memberInfoList[slave]['nickname']}！花费了${slavevalue}金币，还剩${currency - slavevalue}金币\n${memberInfoList[slave]['nickname']}获得了${slavevalue}金币，现在拥有${slavecurrency + slavevalue}金币，身价上涨${slavevalue}->${slavevalue + 20}`]);
            } else {
                const formerOwnerData = await getPlayerData(ID[1], slaveMaster);

                userData['currency'] = parseFloat((userData['currency'] - slavevalue).toFixed(1));
                userData['slave'].push(slave);
                userData['lastPurchaseTime'] = currentSecond;
                storagePlayerData(ID[1], ID[0], userData);
                slaveData['currency'] = parseFloat((slaveData['currency'] + slavevalue).toFixed(1));
                slaveData['value'] = parseFloat((slaveData['value'] + 20).toFixed(1));
                slaveData['master'] = ID[0];
                storagePlayerData(ID[1], slave, slaveData);
                formerOwnerData['currency'] = parseFloat((formerOwnerData['currency'] + slavevalue).toFixed(1));
                formerOwnerData['slave'] = formerOwnerData['slave'].filter(a => a !== slave);
                storagePlayerData(ID[1], slaveMaster, formerOwnerData);

                if (!memberInfoList[slaveMaster]) {
                    deletePlayerData(ID[1], slaveMaster);
                    return e.reply([`${slaveMaster}已不在本群，已删除该用户存档\r已将其仆人解放`]);
                }

                return e.reply([`成功从${memberInfoList[slaveMaster]['nickname']}那里雇佣了${memberInfoList[slave]['nickname']}！花费了${slavevalue}金币，还剩${currency - slavevalue}金币\n${memberInfoList[slaveMaster]['nickname']}获得了${slavevalue}金币，现在拥有${formerOwnerData['currency']}金币\n${memberInfoList[slave]['nickname']}额外获得了${slavevalue / 10}金币，现在拥有${slavecurrency + slavevalue / 10}金币，身价上涨${slavevalue}->${slavevalue + 20}`]);
            }
        } catch (error) {
            console.error('雇佣仆人时发生错误:', error);
            return e.reply(['雇佣仆人时发生错误，请稍后再试']);
        }
    }

}